﻿/*
    This file is part of News Worm.

    News Worm is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    News Worm is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with News Worm.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;

namespace NewsWorm {
    internal partial class ScriptsDialog : Form {
        public ScriptsDialog( ref IScriptManager manager, Point location ) {
            InitializeComponent();
            this.Location = location;
            m_Manager = manager;
            NewScript();
            NewsWorm.NativeMethods.SetWindowTheme( checkedListBoxScripts.Handle, "explorer", null );
            this.Font = SystemFonts.MessageBoxFont;
            textBoxEditor.ShowLineNumbers = true;
            this.checkedListBoxScripts.ContextMenu = contextMenuScripts;
            textBoxErrors.Visible = false;
        }

        private IScriptManager m_Manager;
        private bool m_PopulatingList = false;
        private bool m_IsSaved = false;
        private int m_SelectedEditIndex;

        public void SetTabPage( int index ) {
            tabControlScripting.SelectedIndex = index;
            PopulateScripts();
        }

        private void NewScript() {
            string script = @"using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;

using NewsWorm;

public class NewsWormScript : INewsWormScript {           

    //Make this informative. Each script must have different description.
    public const string DESC = ""Description of the script"";
 
    //This will be called when the script is activated
    public void Activate(IScriptingEvents events) {

        //TODO: Your initialization code here
        
    }

}";
            this.textBoxEditor.Text = script;
            m_IsSaved = false;
        }

        private void EditSelectedScript() {

        }

        private void SaveScript() {
            string name = Guid.NewGuid().ToString();
            string path = Variables.BasePath + "scripts\\" + name;
            try {
                
                if ( !Directory.Exists( Variables.BasePath + "scripts" ) )
                    Directory.CreateDirectory( Variables.BasePath + "scripts" );

                File.WriteAllText( path, textBoxEditor.Text );

                Script script = new Script( textBoxEditor.Text, path, ScriptParser.ParseScriptDescription( textBoxEditor.Text ), name, false,
                    DateTime.Now);
              
                m_Manager.Scripts.Add( script );
                m_IsSaved = true;
            } catch ( Exception e ) {
                new MyMessageBoxError( e.Message, e.StackTrace ).ShowDialog();
            }
        }

        private void PopulateScripts() {
            m_PopulatingList = true;
            checkedListBoxScripts.Items.Clear();

            foreach ( Script s in m_Manager.Scripts )
                checkedListBoxScripts.Items.Add( s, s.Enabled );

            checkedListBoxScripts.Focus();
            m_PopulatingList = false;
        }

        private void tabControlScripting_Selected( object sender, TabControlEventArgs e ) {
            if ( e.TabPageIndex == 1 ) {
                PopulateScripts();
            } //tabpageindex
        }

        private void checkedListBoxScripts_ItemCheck( object sender, ItemCheckEventArgs e ) {
            if ( !m_PopulatingList ) {
                Script script = (Script)( (CheckedListBox)sender ).Items[e.Index];
                if ( e.NewValue == CheckState.Checked ) {
                    if ( ScriptValidate() ) {
                        m_Manager.GetScriptByGuid( script.Guid ).Enabled = true;
                        List<string> errors = m_Manager.Instantiate( script );
                        textBoxErrors.Text = "";
                        if ( errors.Count > 0 ) {
                            textBoxErrors.Visible = true;
                            foreach ( string error in errors )
                                textBoxErrors.Text += error;
                            tabControlScripting.SelectedIndex = 0;
                            m_Manager.GetScriptByGuid( script.Guid ).Enabled = false;
                            
                        } else {
                            if ( textBoxErrors.Visible == true ) {
                                textBoxErrors.Visible = false;
                            }
                        }
                    } else {
                        tabControlScripting.SelectedIndex = 0;
                    }
                } else {
                    m_Manager.GetScriptByGuid( script.Guid ).Enabled = false;
                }

                try {
                    string path = Variables.BasePath + "scripts\\settings\\";

                    if ( !Directory.Exists( path ) )
                        Directory.CreateDirectory( path );

                    StreamWriter writer = new StreamWriter( path + "status.dat", false );

                    foreach ( Script s in m_Manager.Scripts ) {
                        writer.WriteLine( s.Guid + "," + s.Enabled.ToString() + "," + s.CreationDate.ToString() );
                    }

                    writer.Close();
                } catch ( Exception ex ) {
                    Console.WriteLine( ex.Message );
                }
            }
        }

        private void newToolStripMenuItemNew_Click( object sender, EventArgs e ) {
            MyMessageBoxAsk ask = new MyMessageBoxAsk( "Current script will be lost. Are you sure?" );
            if ( ask.ShowDialog() == System.Windows.Forms.DialogResult.Yes ) {
                NewScript();
            }
        }

        private void saveToolStripMenuItemSave_Click( object sender, EventArgs e ) {
            if(!m_IsSaved)
                SaveScript();
        }

        private void textBoxEditor_TextChanged( object sender, FastColoredTextBoxNS.TextChangedEventArgs e ) {
            m_IsSaved = false;
        }

        private void fileToolStripMenuItem_Click( object sender, EventArgs e ) {
            if ( m_IsSaved ) {
                saveToolStripMenuItemSave.Enabled = false;
            } else {
                saveToolStripMenuItemSave.Enabled = true;
            }
        }

        private void contextMenuScripts_Popup( object sender, EventArgs e ) {
            contextMenuScripts.MenuItems.Clear();

            if ( checkedListBoxScripts.SelectedItem != null ) {

                contextMenuScripts.MenuItems.Add( "&Edit",
                            new EventHandler( this.contextMenuScriptsItemEdit_OnClick ) );

                contextMenuScripts.MenuItems.Add( "&Delete",
                    new EventHandler( this.contextMenuScriptsDelete_OnClick ) );
            }
        }

        protected void contextMenuScriptsItemEdit_OnClick( Object sender, EventArgs e ) {
            Script s = (Script)checkedListBoxScripts.SelectedItem;
            textBoxEditor.Text = s.Source;
            tabControlScripting.SelectedIndex = 0;
            m_SelectedEditIndex = checkedListBoxScripts.SelectedIndex;
        }

        protected void contextMenuScriptsDelete_OnClick( Object sender, EventArgs e ) {
            Script s = (Script)checkedListBoxScripts.SelectedItem;
            m_Manager.Scripts.Remove( s );
            checkedListBoxScripts.Items.Remove( checkedListBoxScripts.SelectedItem );
            m_Manager.DeleteScriptFromFileSystemByGuid( s.Guid );
        }

        private void validateToolStripMenuItem_Click( object sender, EventArgs e ) {
            ScriptValidate();
        }

        private bool ScriptValidate() {
            List<string> errors = m_Manager.Validate( textBoxEditor.Text );
            bool retval = true;
            textBoxErrors.Text = "";
            if ( errors.Count > 0 ) {
                textBoxErrors.Visible = true;
                foreach ( string error in errors )
                    textBoxErrors.Text += error;
                retval = false;
            } else {
                if ( textBoxErrors.Visible == true ) {
                    textBoxErrors.Visible = false;
                }
            }

            return retval;
        }

        private void ScriptsDialog_KeyDown( object sender, KeyEventArgs e ) {
            if ( e.KeyCode == Keys.Escape ) {
                if ( textBoxErrors.Visible == true ) {
                    textBoxErrors.Visible = false;
                }
            }
        }

        private void newsWormScriptingToolStripMenuItem_Click( object sender, EventArgs e ) {
            try {
                Process.Start( "http://www.newsworm.net/help/#scripting" );
            } catch ( Exception ex ) {
                new MyMessageBoxError( ex.Message, ex.StackTrace ).ShowDialog();
            }
        }

     
     
    }
}
